package per.dg.retrofittestkotlin.project.home

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.paging.PagedList
import com.google.gson.JsonObject
import per.dg.retrofittestkotlin.project.model.Article
import per.dg.retrofittestkotlin.project.model.ArticleList
import per.dg.retrofittestkotlin.project.model.BaseResult
import per.dg.retrofittestkotlin.use.RetrofitHttpManager
import per.dg.retrofittestkotlin.use.RetrofitHttpManagerFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class HomeViewModel : ViewModel() {

//    var homeArticleListLiveData = MutableLiveData<PagedList<Article>>()
    var homeArticleListLiveData = MutableLiveData<MutableList<Article>>()
    private var homeArticleList = mutableListOf<Article>();
//    private var homeArticleList = PagedList<Article>();

    var retrofitHttpManager : RetrofitHttpManager = RetrofitHttpManagerFactory().creat()

    fun getHomeArticleList(page: Int){
        retrofitHttpManager.wanAndroidApi.homeArticleList(page).also {
            it.enqueue(object : Callback<BaseResult<ArticleList>> {
                override fun onFailure(call: Call<BaseResult<ArticleList>>?, t: Throwable?) {
//                    TODO("Not yet implemented")
                    Log.e("onFailure: ", "")
                }

                override fun onResponse(call: Call<BaseResult<ArticleList>>?, response: Response<BaseResult<ArticleList>>?) {
                    var articleList : MutableList<Article>? = response?.body()?.data?.datas
                    if (articleList != null) {
                        homeArticleList.addAll(articleList)
                    }
                    homeArticleListLiveData.value = homeArticleList
                }

            })

        }
    }

}